﻿using BatchPrint.Extensions;
using BatchPrint.Models;
using BatchPrint.Services;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using MessageBox = System.Windows.Forms.MessageBox;

namespace BatchPrint.Windows;

public partial class ProgressWindowViewModel : ObservableObject
{
    public event Action? OnPrintFinish;

    private readonly PrinterManager _printerManager;

    public ProgressWindowViewModel(PrinterManager printerManager)
    {
        _printerManager = printerManager;
        Files = [];
        ShowPrintProcess = Visibility.Hidden;
    }

    [NotifyPropertyChangedFor(nameof(CurrentFile))]
    [NotifyPropertyChangedFor(nameof(ProgressString))]
    [ObservableProperty]
    private int _progress;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(Count))]
    private ObservableCollection<PrintModel> _files;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SelectedImage))]
    private PrintModel? _selected;

    [ObservableProperty]
    private Visibility _showPrintProcess;

    public int Count => Files.Count;

    public string CurrentFile => Files.Count == 0 ? string.Empty : Path.GetFileName(Files[Progress].FilePath);

    public string ProgressString => $"{Progress + 1}/{Count}";

    public string? PrintName { get; set; }

    public BitmapSource? SelectedImage
    {
        get
        {
            if (Selected == null)
                return null;

            return Selected.Image.ConvertToBitmapImage();
        }
    }

    [RelayCommand]
    private async Task Print()
    {
        ShowPrintProcess = Visibility.Visible;
        await Task.Run(async () =>
        {
            for (var i = 0; i < Count; i++)
            {
                var file = Files[i];
                App.Current.Dispatcher.Invoke(() => Progress = i);
                await Task.Delay(200);
                _printerManager.PrintFile(file.Image, PrintName);
            }
            App.Current.Dispatcher.Invoke(() => MessageBox.Show("打印已完成", "提示", MessageBoxButtons.OK));
            OnPrintFinish?.Invoke();
        });
        ShowPrintProcess = Visibility.Hidden;
    }

    [RelayCommand]
    private void Cancel()
    {
        OnPrintFinish?.Invoke();
    }
}
